package com.yokead.service.nginxlog;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.jiangzeyin.common.JsonMessage;
import cn.simplifydb.database.base.BaseRead;
import cn.simplifydb.database.run.read.IsExists;
import cn.simplifydb.database.run.read.Select;
import cn.simplifydb.database.run.read.SelectPage;
import cn.simplifydb.database.run.write.Remove;
import com.alibaba.druid.util.JdbcUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.regexp.internal.RE;
import com.yokead.database.DatabaseContextHolder;
import com.yokead.nginxlog.entity.Nginx_Log_2019;
import com.yokead.system.log.SystemLog;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 新版
 * nginx日志表服务
 *
 * @author yangheng
 */
@Service
public class NginxLog2019Service {

    /**
     * 保存一条日志记录
     *
     * @param item 需要被保存的数据
     */
    public void insertItem(Nginx_Log_2019 item) {
        String sql = StrUtil.format(
                "INSERT INTO Nginx_Log_2019(ip,xip,time,type,url,status,referer,uag,createTime) VALUES('{}','{}','{}','{}','{}','{}','{}','{}',{});"
                , item.getIp()
                , item.getXip()
                , item.getTime()
                , item.getType()
                , item.getUrl()
                , item.getStatus()
                , item.getReferer()
                , item.getUag()
                , "UNIX_TIMESTAMP(NOW())"
        );
        try {
            System.out.println(sql);
            DataSource dataSource = DatabaseContextHolder.getDataSource();
            JdbcUtils.execute(dataSource, sql);
        } catch (Exception e) {
            SystemLog.ERROR().error("插入nginxLog出现异常", e);
        }
    }

    /**
     * 保存多条记录
     *
     * @param list list
     */
    public void insertList(List<Nginx_Log_2019> list) {
        if (CollUtil.isEmpty(list)) {
            SystemLog.ERROR().error("空的日志列表。无法进行写入操作");
        }
        StringBuilder insertTemp = new StringBuilder(" INSERT INTO Nginx_Log_2019(ip,xip,time,type,url,status,referer,uag,filePath,domain,createTime) VALUES ");
        String insertValuesTemp = " ('{}','{}','{}','{}','{}','{}','{}','{}','{}','{}',{}) ";
        String insertValues = list.stream().map(item -> StrUtil.format(insertValuesTemp
                , item.getIp()
                , item.getXip()
                , item.getTime()
                , item.getType()
                , item.getUrl()
                , item.getStatus()
                , item.getReferer()
                , item.getUag()
                , item.getFilePath()
                , item.getDomain()
                , "UNIX_TIMESTAMP(NOW())"
        )).collect(Collectors.joining(","));
        insertTemp.append(insertValues);
        try {
            DataSource dataSource = DatabaseContextHolder.getDataSource();
            JdbcUtils.execute(dataSource, insertTemp.toString());
        } catch (Exception e) {
            SystemLog.ERROR().error("插入nginxLog出现异常", e);
        }
    }


    /**
     * 获取一条数据
     *
     * @param condition 搜索条件
     * @return JSONObject
     */
    public JSONObject queryOne(String condition, String columns) {
        Select<?> select = generateSelect(BaseRead.Result.JsonObject, Nginx_Log_2019.class);
        select.where(condition);
        select.limit(1);
        select.setColumns(columns);
        return select.run();
    }

    /**
     * 判断这个文件有没有被分析过
     *
     * @param logFilePath 文件路径
     * @return boolean
     */
    public boolean isExists(String logFilePath) {
        IsExists<Nginx_Log_2019> isExists = new IsExists<Nginx_Log_2019>() {
        };
        isExists.where(StrUtil.format("filePath ='{}'", logFilePath));
        return isExists.runBoolean();
    }

    /**
     * 获取多条数据
     *
     * @param condition 搜索条件
     * @return JSONObject
     */
    public JSONArray queryList(String condition, String columns) {
        Select<?> select = generateSelect(BaseRead.Result.JsonArray, Nginx_Log_2019.class);
        select.where(condition);
        select.setColumns(columns);
        return select.run();
    }


    Select<?> generateSelect(BaseRead.Result resultType, Class entityClass) {
        String tableName = entityClass.getSimpleName();
        Select<?> select = new Select() {
        };
        select.setTag("core");
        select.setResultType(resultType);
        select.from(tableName);
        return select;
    }

    SelectPage<?> generateSelectPage(int page, int limit, Class entityClass) {
        String tableName = entityClass.getSimpleName();
        SelectPage<?> selectPage = new SelectPage(BaseRead.Result.PageResultType) {
        };
        selectPage.setPageNoAndSize(page, limit);
        selectPage.setTag("core");
        selectPage.from(tableName);
        return selectPage;
    }

    public String list() {
        Select<?> select = generateSelect(BaseRead.Result.JsonArray, Nginx_Log_2019.class);
        select.limit(10);
        JSONArray run = select.run();
        return JsonMessage.getString(200, "", run);
    }

    /**
     * 删除三个月前的数据
     */
    public void deleteOldData() {
        DateTime offset = DateUtil.offset(new DateTime(), DateField.MONTH, -3);
        long l = offset.getTime() / 1000;

        Remove<Nginx_Log_2019> remove = new Remove<Nginx_Log_2019>(Remove.Type.delete) {
        };
        remove.where("createTime <=?");
        remove.addParameters(l);
        remove.run();
    }
}
